package com.xinke.juc.case04;

import com.xinke.juc.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：xinke
 * @Date：2025/10/4
 * @Desc: 哲学家就餐问题 - ReentrantLock
 */
public class Philosopher02 {
    public static void main(String[] args) {
        ChopstickReentrantLock c1 = new ChopstickReentrantLock("1");
        ChopstickReentrantLock c2 = new ChopstickReentrantLock("2");
        ChopstickReentrantLock c3 = new ChopstickReentrantLock("3");
        ChopstickReentrantLock c4 = new ChopstickReentrantLock("4");
        ChopstickReentrantLock c5 = new ChopstickReentrantLock("5");
        new PhilosopherReentrantLock("苏格拉底", c1, c2).start();
        new PhilosopherReentrantLock("柏拉图", c2, c3).start();
        new PhilosopherReentrantLock("亚里士多德", c3, c4).start();
        new PhilosopherReentrantLock("赫拉克利特", c4, c5).start();
        new PhilosopherReentrantLock("阿基米德", c5, c1).start();
    }
}

// 筷子类
@Slf4j
class ChopstickReentrantLock extends ReentrantLock {
    String name;

    public ChopstickReentrantLock(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}

@Slf4j
class PhilosopherReentrantLock extends Thread {
    ChopstickReentrantLock left;
    ChopstickReentrantLock right;

    public PhilosopherReentrantLock(String name, ChopstickReentrantLock left, ChopstickReentrantLock right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    private void eat() {
        log.info("eating...");
        Sleeper.sleep(1);
    }

    @Override
    public void run() {
        while (true) {
            // 获得左手筷子
            if (left.tryLock()) {
                try {
                    // 获得右手筷子
                    if (right.tryLock()) {
                        try {
                            // 吃饭
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
                // 放下右手筷子
            }
            // 放下左手筷子
        }
    }
}
